package com.feizhi.inventory.fragment.inventorysheet;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.bean.InventoryBean;
import com.feizhi.inventory.database.Task;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.databinding.FragmentInventorySheetBinding;
import com.feizhi.inventory.fragment.inventory.InventoryAdapter;
import com.feizhi.inventory.util.Util;

import java.util.ArrayList;
import java.util.List;

/**
 *  盘点单号
 * */
public class InventorySheetFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener {
    Util util = new Util();
    public FragmentInventorySheetBinding mBinding;
    private MainActivity mActivity;
    List<Task> list;

    TaskDetailsDao taskDetailsDao;
    List<TaskDetails> taskDetails;

    List<TaskDetails> taskDetailsList = new ArrayList<>();
    List<Task> taskList = new ArrayList<>();
    private TaskMyAdapter adapter;
    private List<InventoryBean> data;
    private TextView titleText;
    TaskDao taskDao;
    private ImageView imageBack;
    DaoSession updaoSession;
    private String sheetDataName;


    public InventorySheetFragment() {

    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();
        updaoSession = ((dbApp) mActivity.getApplication()).getDaoSession();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentInventorySheetBinding.inflate(inflater);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化控件
        initView();
        //处理事件
        setOnClickListener();
    }

    private void setOnClickListener() {
        List<String> names = new ArrayList<>();


        for (int i = 0; i < list.size(); i++) {

            names.add(list.get(i).getTask_ID());

        }

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mActivity, android.R.layout.simple_dropdown_item_1line, names);
        mBinding.edtSearch.setAdapter(arrayAdapter);
        mBinding.edtSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mBinding.edtSearch.showDropDown();

                // 请求输入框获取焦点，弹出软键盘
                mBinding.edtSearch.requestFocus();
                mBinding.edtSearch.requestFocusFromTouch();
                InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(mBinding.edtSearch, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        mBinding.edtSearch.setOnEditorActionListener(this);

        imageBack.setOnClickListener(this);
        adapter.setOnClickListener(new TaskMyAdapter.OnCliekListener() {
            @Override
            public void setItemOnClickListener(int position) {
                String tid = taskList.get(position).getTask_ID();
                Bundle bundle = new Bundle();
                bundle.putString("tid", tid);
                bundle.putString("sheetDataName", sheetDataName);

                Navigation.findNavController(mActivity, R.id.fragment_my).navigate(R.id.exportDetailsFragment, bundle);

            }
        });
        adapter.setItemLongClickListener(new InventoryAdapter.ItemOnLongClickListener() {
            @Override
            public void ItemLongClickListener(int position) {
                AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("确定要删除：" + taskList.get(position).getTask_ID() + "吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String id = taskList.get(position).getTask_ID();
                               // DELETE FROM 表名 WHERE 条件;
                                String sql = "DELETE FROM " +
                                        updaoSession.getTaskDao().getTablename() +
                                        " WHERE " +
                                        TaskDao.Properties.Task_ID.columnName +
                                        " = " +
                                        '"' + id + '"';
                                updaoSession.getDatabase().execSQL(sql);


                                String sql1 = "DELETE FROM " +
                                        updaoSession.getTaskDetailsDao().getTablename() +
                                        " WHERE " +
                                        TaskDetailsDao.Properties.TaskID.columnName +
                                        " = " +
                                        '"' + id + '"';
                                updaoSession.getDatabase().execSQL(sql1);

                                taskList.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();

            }
        });

    }

    private void initView() {


        Bundle bundle = getArguments();
        if (bundle != null) {
            sheetDataName = bundle.getString("mainDataName");
        }

        titleText = mActivity.findViewById(R.id.title_text);
        imageBack = mActivity.findViewById(R.id.title_back);
        imageBack.setVisibility(View.VISIBLE);

        titleText.setText("盘点单");


        DaoSession daoSession = ((dbApp) mActivity.getApplicationContext()).getDaoSession();
        taskDao = daoSession.getTaskDao();

        try {
            list = taskDao.queryBuilder().where(TaskDao.Properties.Task_state.eq("已盘点")).list();
        }catch (Exception e) {
            e.printStackTrace();
        }


        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new TaskMyAdapter(taskList, mActivity, this);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        onRefresh();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:

                Navigation.findNavController(mActivity, R.id.fragment_my).navigateUp();
                break;
            default:break;
        }
    }

    private void refresh() {


        if (list.isEmpty()) {
            mBinding.recyclerView.setVisibility(View.GONE);
        }
        else {
            mBinding.recyclerView.setVisibility(View.VISIBLE);
        }
        //清空数据，防止重复
        if (!taskList.isEmpty()) {
            taskList.clear();
        }

        taskList.addAll(list);
        adapter.setData(taskList);
        for (int i = 0; i < taskList.size(); i++) {

        }

        //清空dao的缓存，因为greendao的缓存机制，是会从缓存中提取数据，所以更新后界面没有更新，但是数据库更新了
        taskDao.detachAll();
    }


    public void onRefresh() {
        refresh();
    }

    @Override
    public boolean onEditorAction(TextView textView, int code, KeyEvent keyEvent) {

        if (code == EditorInfo.IME_ACTION_DONE ||
                (keyEvent != null && keyEvent.getKeyCode() == keyEvent.KEYCODE_ENTER)) {
            list = taskDao.queryBuilder().where(TaskDao.Properties.Task_state.eq("已盘点")).list();
            hideKeyboard();
            taskList.clear();
            for (int i = 0; i < list.size(); i++) {

                if (list.get(i).getTask_ID().contains(mBinding.edtSearch.getText().toString())) {
                    taskList.add(list.get(i));
                }
                adapter.setData(taskList);
            }

            mBinding.edtSearch.setText("");
            return true;

        }
        return false;
    }

    private void hideKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(mBinding.edtSearch.getWindowToken(), 0);
        }
    }
}